import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:t3_data_service/biz_data_source/map/address/city_pick/model/city_pick_models.dart';
import 'package:t3_data_service/biz_data_source/map/address/city_pick/model/host_model.dart';
import 'package:t3_foundation/t3_foundation.dart';
import 'package:t3_map/address_select.dart';
import 'package:t3_map/configs/poi_search_base_config.dart';
import 'package:t3_map/data_report/address_log.dart';
import 'package:t3_track/t3_track.dart';
import 'package:uikit/uikit.dart';

import '../model/absorbed_end_point.dart';
import '../view_model/bottom_selected_poi_view_model.dart';
import '../view_model/map_selected_header_view_model.dart';

class MapSelectedPOIPageController {
  final BasicMessageChannel channel;
  final MapSelectConfig config;
  
  var bottomSelectedPOIViewModel = bindVM(BottomSelectedPOIViewModel());
  var headerViewModel = bindVM(MapSelectedHeaderViewModel());

  var withContainer = true;
  MapSelectedPOIPageController(this.channel, this.config) {
    headerViewModel.updateCity(HostModel(
      city: config.location?.cityName,
      adCode: config.location?.adCode,
    ));
    headerViewModel.updatePOI(config.poi);
    logMapSelectDebug('图选控制器初始化');
  }

  void dispose() {
    logMapSelectDebug('图选控制器销毁');
    deleteVM(bottomSelectedPOIViewModel);
    deleteVM(headerViewModel);
  }

  Future<Object?> handlerMsg(Object? message) async {
    if (message != null) {
      final map = message as Map?;
      if (map != null) {
        var name = map["action"] as String?;
        logMapSelectDebug('收到原生容器消息:$name');

        if (name == 'singlePoiChanged') {
          var data = map['data'] as Map<dynamic, dynamic>?;
          var location = LatLng.fromJson(data?['location']);
          if (location != null) {
            var poi = POIModel(location: location);
            poi.name = data?['name'];
            poi.address = data?['address'];
            logMapSelectDebug('图选起点：${poi.name}');
            bottomSelectedPOIViewModel.updateSinglePOI(poi);
          }

          var cityData = data?['city'] as Map?;
          if (cityData != null) {
            var cityName = cityData['city'];
            var cityCode = cityData['cityCode'];
            var adCode = cityData['adCode'];
            var host = HostModel(city: cityName, amapCityCode: cityCode, adCode: adCode, latitude: location?.lat, longitude:location?.lng);
            logMapSelectDebug('图选起点：${host.city}');
            headerViewModel.updateCity(host);
          }
        }
        if (name == 'singlePoiButtonStatus') {
          var enable = (map['data'] as bool?) ?? (bottomSelectedPOIViewModel.singlePointPOI.value.isValid ? true : false) ;
          logMapSelectDebug('底部的确定按钮是否可以点击确定:$enable');
          bottomSelectedPOIViewModel.updateButtonEnable(enable);
        }
        if (name == 'hiddenBottom') {
          var hidden = (map['data'] as bool?);
          if (hidden !=null) {
            logMapSelectDebug('围栏选点时需要隐藏Flutter的底部选择框:$hidden');
            bottomSelectedPOIViewModel.updateHiddenBottomView(hidden);
          }
        }
        if (name == 'fenceClickAddress') {
          logMapSelectDebug('围栏点击了重新搜索按钮');
          clickSearchBar();
        }
        if (name == 'multiPoiChanged') {
          var data = map['data'] as List<dynamic>;
          List<T3AbsorbedEndPoint> points = [];
          for (var item in data) {
            var p = T3AbsorbedEndPoint.fromJson(item);
            if (p.isValid) {
              points.add(p);
            }
          }
          var poi = map['poi'] as Map<dynamic, dynamic>?;
          var location = LatLng.fromJson(poi?['location']);
          if (location != null) {
            var model = POIModel(location: location);
            model.name = poi?['name'];
            model.address = poi?['address'];
            var lat = poi?['location']['lat'] as double? ?? 0;
            var lng = poi?['location']['lng'] as double ?? 0;
            model.location = LatLng(lat, lng);
            bottomSelectedPOIViewModel.updateMultiPoints(model, points);
            logMapSelectDebug('多点选择器返回结果：${points.length}个点, ${model.toJson().toString()}');
          }
          var cityData = map?['city'] as Map?;
          if (cityData != null) {
            var cityName = cityData['city'];
            var cityCode = cityData['cityCode'];
            var adCode = cityData['adCode'];
            var host = HostModel(city: cityName, amapCityCode: cityCode, adCode: adCode, latitude: location?.lat, longitude:location?.lng);
            logMapSelectDebug('图选起点：${host.city}');
            headerViewModel.updateCity(host);
          }
        }
      }
    }
    return null;
  }

  sendMessageToNativeContainer(String action, dynamic data) {
    var message = {
      'action' : action,
      'data' : data,
    };
    logMapSelectDebug('Flutter向原生发生消息：${message.toString()}');
    channel.send(message);
  }
}

extension MapSelectedPOIPageControllerBottomEvent on MapSelectedPOIPageController {
  void clickLocationButton() {
    sendMessageToNativeContainer('clickLocationButton', null);
  }

  void clickPointsListAtIndex(int index) {
    sendMessageToNativeContainer('clickIndexButton', index);
  }

  void clickSureButton() async {
    if (Platform.isAndroid) {
      BoostNavigator.instance.pop({
        'isAnimated' :false
      });
    }
    sendMessageToNativeContainer(
        'clickBottomButton',
        bottomSelectedPOIViewModel.selectedPoint.value.index
    );
  }

  void clickConfusionAtIndex(int index) {
    sendMessageToNativeContainer('clickConfusionIndexButton', index);
  }

  void clickPOISearchPageResult(Map data) {
    sendMessageToNativeContainer('selectedPOI', data);
  }
}

extension MapSelectedPOIPageControllerHeaderEvent on MapSelectedPOIPageController {
  void clickBackButton() {
    if (config.pointType != T3POIType.start) {
      T3Track.trackClick("0199.165.003.004");
    }
    if (config.mode == T3MapSelectMode.confusion && bottomSelectedPOIViewModel.singlePointPOI.value.isValid) {
      bottomSelectedPOIViewModel.updateSinglePOI(POIModel(location: const LatLng(0, 0)));
    }
    sendMessageToNativeContainer('clickBackButton', null);
  }

  void clickCancel() async {
    if (config.pointType == T3POIType.start) {
      T3Track.trackClick('0199.007.000.004');
    } else {
      T3Track.trackClick("0199.165.003.003");
    }
    BoostChannel.instance.sendEventToNative("cancelAddressSelect", {
      "action" : 'mapSearchHeader'
    });
  }

  void clickCity(BuildContext context) {
      if (config.pointType == T3POIType.start) {
        T3Track.trackClick('0199.007.001.001');
      } else {
        T3Track.trackClick('0199.165.003.002');
      }

      var uuid = randomString();
      DataBus.global.listen<CityPickResultEvent>((p0) async {
        logMapSelectDebug('监听到城市选择结果：${p0.hostModel.toJson().toString()}');
        if (p0.uuid == uuid) {
          var city = p0.hostModel;
          if ((city.adCode ?? '').isEmpty || (city.city ?? '').isEmpty || ((city.longitude ?? 0) == 0) ||
              ((city.latitude ?? 0) == 0)) {
            return;
          }
          /// 选择城市后进入搜索页面
          var inLocation = T3POILocation(
              adCode: city.adCode ?? '',
              cityName: city.city ?? '',
              coordinate: LatLng(city.latitude ?? 0, city.longitude ?? 0)
          );
          POISearchSinglePointConfig searchConfig = createSinglePointConfig(inLocation);
          var json = searchConfig.toJson();
          json['animation_style'] = 'push';
          logMapSelectDebug('城市切换后跳转搜索页面：${json.toString()}');
          var result = await openSinglePointPOISearchPage(searchConfig, isPresent:false);
          if (result != null) {
            if (result is Map) {
              var model = result['data'] as List<Map>?;
              if (model != null && model.isNotEmpty) {
                /// 防止多次Pop带来的问题
                Future.delayed(const Duration(milliseconds: 100), () {
                  BoostNavigator.instance.pop();
                });
                logMapSelectDebug('搜索选择了点：${model.first.toString()}');
                clickPOISearchPageResult(model.first);
                var poi = POIModel.fromJson(model.first);
                headerViewModel.updatePOI(poi);
                return;
              }
            }
          }
        }
      });

      BoostNavigator.instance.push('cityPickerPage', arguments: {
        'hintText': config.pointType.cityPlaceHolder(),
        'cityScope' : config.cityScope.value,
        'autoPop':false,
        'showBack':true,
        'isFromFlutter' : true,
        'uuid':uuid,
      }, withContainer: withContainer);
  }

  POISearchSinglePointConfig createSinglePointConfig(T3POILocation? inLocation) {
    POISearchSinglePointConfig searchConfig;
    if (inLocation != null) {
      searchConfig = POISearchSinglePointConfig(location: inLocation);
    } else {
      var host = headerViewModel.city.value;
      var currentPoi = bottomSelectedPOIViewModel.singlePointPOI.value;

      var adCode = config.location?.adCode;
      var city = config.location?.cityName;
      var coor = config.location?.coordinate;
      if (host.adCode.isNotNullAndEmpty()) {
        adCode = host.adCode;
      } else {
        if (currentPoi.adCode.isNotNullAndEmpty()) {
          adCode = currentPoi.adCode;
        }
      }
      if (host.city.isNotNullAndEmpty()) {
        city = host.city;
      } else if (currentPoi.city.isNotNullAndEmpty()) {
        city = currentPoi.city;
      }
      if (host.latitude != 0 && host.longitude != 0 && host.latitude != null && host.longitude != null) {
        coor = LatLng(host.latitude!, host.longitude!);
      } else if (LatLng.isLatLngValid(currentPoi.location)) {
        coor = currentPoi.location;
      }
      var location = T3POILocation(
          adCode: adCode ?? '',
          cityName: city ?? '',
          coordinate: coor ?? const LatLng(0, 0),
      );
      searchConfig = POISearchSinglePointConfig(location: location);
    }
    searchConfig.style = config.style;
    searchConfig.cityScope = config.cityScope;
    searchConfig.shouldCheckTableSelectedPoi = false;
    searchConfig.showBackButton = true;
    searchConfig.pointType = config.pointType;
    searchConfig.showMapSelectedFooter = false;
    searchConfig.entryOptions = [T3EntryOptions.homeAndCompany];
    searchConfig.showConfusionButton = false;
    if (inLocation == null && headerViewModel.currentPOI.value.name != null) {
      searchConfig.defaultText = headerViewModel.currentPOI.value.name;
    }
    searchConfig.pageScene = PageScene.mapSelectSearch;
    return searchConfig;
  }

  void clickSearchBar() async {
    if (config.pointType == T3POIType.start) {
      T3Track.trackClick('0199.007.001.003');
    } else {
      T3Track.trackClick('0199.165.003.001');
    }

    POISearchSinglePointConfig searchConfig = createSinglePointConfig(null);
    var json = searchConfig.toJson();
    json['animation_style'] = 'push';
    logMapSelectDebug('点击搜索框，进入搜索页面：${json.toString()}');
    var result = await openSinglePointPOISearchPage(searchConfig,isPresent:false);
    if (result != null) {
      if (result is Map) {
        var model = result['data'] as List<Map>?;
        if (model != null && model.isNotEmpty) {
          clickPOISearchPageResult(model.first);
          logMapSelectDebug('搜索选择了点：${model.first.toString()}');
          var poi = POIModel.fromJson(model.first);
          headerViewModel.updatePOI(poi);
          return;
        }
      }
    }
  }
}